package com.pdf.pdfserver.service.read.image.pdf;

import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author songfz
 * @Description   回调接口 接收 PdfContentStreamProcessor 反馈
 * @Date 2022/3/2
 */
public  class ImageRenderListener implements RenderListener {

    private static  Logger LOG = LoggerFactory.getLogger(ImageRenderListener.class);
    private String imagePath;

    public ImageRenderListener(String imagePath) {
        this.imagePath = imagePath;
    }

    @Override
    public void beginTextBlock() {

    }

    @Override
    public void renderText(TextRenderInfo renderInfo) {

    }

    @Override
    public void endTextBlock() {

    }

    /**
     * 读取图片
     * @param renderInfo
     */
    @Override
    public void renderImage(ImageRenderInfo renderInfo) {
        FileOutputStream os = null;
        try {
            PdfImageObject image = renderInfo.getImage();
            if (image == null) {
                return;
            }
            os = new FileOutputStream(imagePath);
            os.write(image.getImageAsBytes());
            os.flush();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}
